package com.jiangdong.craft.util;

import com.jiangdong.craft.example.CraftProcedureExample;
import com.jiangdong.craft.mapper.CraftProcedureMapper;
import com.jiangdong.craft.mapper.ProcedureMapper;
import com.jiangdong.craft.mapper.RelationMapper;
import com.jiangdong.craft.entity.CraftProcedure;
import com.jiangdong.craft.entity.Procedure;
import com.jiangdong.craft.entity.Relation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class CraftUtil {

    @Autowired
    CraftProcedureMapper craftProcedureMapper;
    @Autowired
    ProcedureMapper procedureMapper;
    @Autowired
    RelationMapper relationMapper;

    /**
     * @param id 根据流程图id获取其节点及节点之间的对应关系
     * @return
     */
    public List<Procedure> getProceduresByCraftId(Integer id){

        CraftProcedureExample craftProcedureExample = new CraftProcedureExample();
        craftProcedureExample.createCriteria().andCraftIdEqualTo(id);
        List<CraftProcedure> craftProcedures = craftProcedureMapper.selectByExample(craftProcedureExample);

        if (!CollectionUtils.isEmpty(craftProcedures)){
            List<Integer> ids = new ArrayList<>();
            for (CraftProcedure craftProcedure : craftProcedures){
                ids.add(craftProcedure.getProcedureId());
            }
            List<Procedure> procedures = procedureMapper.selectBatchById(ids);

            List<Relation> relations = relationMapper.selectByExample(null);

            for (Procedure procedure : procedures){
                procedure = saveRelation(relations,procedure,id);
            }
            return procedures;
        }

        return null;
    }


    /**
     * @param relationList 节点关系集合
     * @param procedure    要封装的节点
     * @return             返回包括节点之间对应关系的节点
     */
    public Procedure saveRelation(List<Relation> relationList,Procedure procedure,Integer craftId){
        List<Integer> frontNode = new ArrayList<>();
        List<Integer> postNode = new ArrayList<>();

            for (Relation relation : relationList){
                if (procedure.getId().equals(relation.getProcedureId()) && relation.getCraftId().equals(craftId)){
                    if (relation.getPrepositionId() != null){
                        frontNode.add(relation.getPrepositionId());
                    }
                    if (relation.getPostpostitionId() != null){
                        postNode.add(relation.getPostpostitionId());
                    }
                }
            }

        procedure.setFrontNodes(frontNode);
        procedure.setPostNodes(postNode);
        return procedure;
    }


}
